<template>
  <div class="container">
    <el-row :gutter="10" type="flex" justify="start" class="mb14">
      <el-col :span="1.5" class="text-align-left">
        <div id="messBox">下列服务编码还未返回预估单：{{ coding }}</div>
        <div class="color-red">
          预估单未返回时请确认以下操作是否已完成：
        </div>
        <div
          v-for="(item, index) in textArray"
          :key="index"
          class="color-red"
        >
          {{ item }}
        </div>
      </el-col>
    </el-row>
        <wz-table :columns="columns" :use-index="true" :table-data="tableData" :getListMethod="getListMethod">
      <template #orderState="{ row }">
        <div>
          {{ orderStateDictionaries(row) }}
        </div>
      </template>
      <template #isPush="{ row }">
        <div>
          {{ isPushDictionaries(row) }}
        </div>
      </template>
      <template #paymentType="{ row }">
        <div>
          {{ payTypeDictionaries(row) }}
        </div>
      </template>
      <!-- 1:新增，2：冲销，3：查看 -->
      <template #operation="{ row }">
        <div>
          <el-button
            v-if="isTrade(row)"
            class="pms-button-primary-plain"
            @click="trade(row)"
          >冲销</el-button>
          <el-button
            v-if="row.isPush == '0'"
            class="pms-button-primary-plain"
            @click="handleDelete(row)"
          >删除</el-button>
          <el-button
            v-if="row.isPush == '0'"
            class="pms-button-primary-plain"
            @click="handleSend(row)"
          >推送商合</el-button>
        </div>
      </template>
    </wz-table>
  </div>
</template>

<script>
import { INDEPENDENT_RESEARCH_TEXT, SHOW_SENDSH_MSG_TIP } from './enum/textEnum'
import { INSPECTION_VALUATION_DETAILS } from './enum/table'
import {
    queryInsValDetails12,
    getServiceReceInspection,
    updateInsVaDetails,
    inspectionValuationPush,
    getWFWorkItem,
    getAcceptanceList
} from '@/api/checkoutValuation/index'
import checkoutValuation from '@/mixins/checkoutValuation'
import {
    getPrjDetailApi
} from '@/api/acceptance/index'
export default {
    name: 'InspectionValuationDetails',
    mixins: [checkoutValuation],
    data() {
        return {
            coding: [],
            textArray: [],
            columns: [],
            tableData: [],
            options: [],
            prjId: '',
            fatherNodeArr: [],
            prjDetail:{
            }
        }
    },
    computed: {
        query() {
            return this.$route.query
        },
        isTrade() {
          return (row) => {
                const fartherNode = this.getParentNode(row)
                const parentNode = Math.abs(Number(fartherNode?.shMoney || 0))
                const flag = Math.sign(row.currentInspectionMoney)
                const childrenShMoney = Math.abs(row.currentInspectionMoney)
                return (+row.isPush !== 0 &&
                this.payTypeDictionaries(row) === '进度款' && this.repairIsTrade(parentNode, childrenShMoney, flag) && !this.getIsAllTrade(fartherNode))
            }
        },
        showOperate(){
           return ['E','F'].includes(this.$route.query.prjStage)&&this.prjDetail.isNewBusiness==='1'&&['25','29'].includes(this.prjDetail.buildModes)
        },
        // 智联服务成本展示时间
         newZlSoftWort(){
            return this.prjDetail.isNewBusiness==='1'&&['25'].includes(this.prjDetail.buildModes)&&this.prjDetail.prjType==='W'
        },
    },
    async mounted() {
        this.textArray = INDEPENDENT_RESEARCH_TEXT
        this.columns = JSON.parse(JSON.stringify(INSPECTION_VALUATION_DETAILS))
        if (this.$route.query.workItemId) {
            const getWFWorkItemRes = await getWFWorkItem({
                workItemId: this.$route.query.workItemId
            })
            if (getWFWorkItemRes.code === '200') {
                this.lcList = getWFWorkItemRes.data // 获取流程参数信息
                this.prjId = getWFWorkItemRes.data.bizObject.prjId
            }
        } else {
            this.prjId = this.$route.query.prjId
        }
        this.getServiceReceInspection({ prjId: this.prjId })
        this.getNewTableList()
        await this.getInitPriDetail()
        if(this.showOperate){
            this.columns = this.columns.filter(item=>item.prop!=='operation')
        }
        // 智联服务成本展示时间字段
        if (!this.newZlSoftWort) {
            const _arrType = ['shareStartDate', 'shareEndDate']
            this.columns = this.columns.filter(item => !_arrType.includes(item.prop))
        }
        
    },
    methods: {
        async getNewTableList(){
            if(this.$route.query.prjStage==='F'){
                const {data} = await getAcceptanceList({
                    prjId: this.prjId,
                })
                this.tableData =data
            }else{
                this.queryInsValDetails12({
                    prjId: this.prjId,
                    supplierCode: this.query.supplierCodes,
                    month: this.query.months
                })
            } 
        },
        getListMethod(){
            console.log("");
        },
        async getInitPriDetail(){
            const { code, data } = await getPrjDetailApi(this.prjId)
            if (+code === 200) {
                this.prjDetail =data
            }
        },
        repairIsTrade(parentNode, childrenShMoney, flag){
            return parentNode === childrenShMoney && flag === 1
        },
        async getServiceReceInspection(params) {
            const { code, data } = await getServiceReceInspection(params)
            if (+code === 200 && data.length > 0) {
                data.map((v) => {
                    this.coding.push(v)
                })
                this.coding = this.coding.join(',')
            } else {
                this.coding = '无'
            }
        },
        async queryInsValDetails12(params) {
            const { code, data } = await queryInsValDetails12(params)
            if (+code === 200 && data.length > 0) {
                this.tableData = data
            for (const item of this.tableData) {
                    if (item.pid === '0') {
                        this.fatherNodeArr.push(item) // 获取所有父节点
                    }
                }
                console.log(this.fatherNodeArr)
            }
        },

        isPushDictionaries(row) {
            switch (row.isPush) {
                case '0':
                    return '未推送'
                case '1':
                    return '已推送'
                case '2':
                    return '推送超时'
                case '3':
                    return '部分推送'
                default:
                    break
            }
        },
        // 付款类型字典转换
        payTypeDictionaries(row) {
            console.log(row.paymentType)
            switch (row.paymentType) {
                case 'FIRST':
                    return '首付款（含安全生产费）'
                case 'PROGRESSING':
                    return '进度款'
                case 'LOSS':
                    return '损失款'
                default:
                    break
            }
        },
        orderStateDictionaries(row) {
            switch (row.orderState) {
                case '1':
                    return '有效'
                case '0':
                    return '无效'
                case '-1':
                    return '冻结'
                default:
                    break
            }
        },
        // 数组插入
        getParent(row) {
            const parentNode = this.tableData.filter((v) => {
                return row.pid === v.vid
            })
            return parentNode
        },
        handleDelete(row) {
            const parentNode = this.getParent(row)
            this.$confirm('确认删除该明细', '删除提醒', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                cancelButtonClass: 'pms-zr-button',
                confirmButtonClass: 'pms-zr-button-primary',
                type: 'warning'
            }).then(async() => {
                const currentInspectionNum = Number(row.currentInspectionNum)
                const currentInspectionMoney = Number(
                    row.currentInspectionMoney
                )
                // const sumNum = Number(parentNode[0].sumNum) // 该订单累计验工数量
                // const sumMoney = Number(parentNode[0].sumMoney) // 该订单累计验工金额
                // const shNum = Number(parentNode[0].shNum) // 该订单累计验工数量
                // const shMoney = Number(parentNode[0].shMoney) // 该订单累计验工金额
                // const diffNum = Number(sumNum) - Number(currentInspectionNum)
                // const diffMoney =
                //     Number(sumMoney) - Number(currentInspectionMoney)
                const data = {
                    onlyBe1Flag: parentNode[0].onlybe1flag,
                    currentInspectionNum: -currentInspectionNum,
                    currentInspectionMoney: -currentInspectionMoney,
                    serviceCode: parentNode[0].serviceCode,
                    prjId: row.prjId,
                    subPrjId: row.subPrjId,
                    pId: row.pid,
                    vId: row.vid,
                    flag: '3',
                     month: this.query.month || '2023-11'
                }
                const updateInsVaDetailsRes = await updateInsVaDetails(data)
                if (updateInsVaDetailsRes.code === '200') {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    })
                }
                this.queryInsValDetails12({
                    prjId: this.prjId || '39994521',
                    supplierCode: this.query.supplierCodes || '020100000307',
                    month: this.query.months || '2023-11'
                })
            })
        },
        handleSend(row) {
            this.$confirm(SHOW_SENDSH_MSG_TIP, '提示', {
                cancelButtonText: '取消',
                    confirmButtonText: '确定',
                    customClass: 'pms-confirm',
                cancelButtonClass: 'pms-zr-button',
                confirmButtonClass: 'pms-zr-button-primary',
                    type: 'warning'
            }).then(() => {
                this.sendSH(row)
            })
        },
        async sendSH(row) {
            const gtIspectionVal = await inspectionValuationPush({
                valuationDetailId: row.vid
            })
            if (gtIspectionVal.code === '200') {
                this.$message({
                    message: gtIspectionVal.message,
                    type: 'success'
                })
                this.queryInsValDetails12({
                    prjId: this.prjId || '39994521',
                    supplierCode: this.query.supplierCodes || '020100000307',
                    month: this.query.months || '2023-11'
                })
            }
        },
        async trade(row) {
            const parentNode = this.getParent(row)[0]
             const currentInspectionMoney = -1 * Math.abs(Number(row.currentInspectionMoney))
            const currentInspectionNum = -1 * Math.abs(Number(row.currentInspectionNum))
            const inspectionTax =
                Number(currentInspectionMoney) * Number(parentNode.taxrate)
            const inspectionTaxAmount =
                Number(currentInspectionMoney) + Number(inspectionTax)
            const params = {
                pId: row.pid,
                prjId: row.prjId,
                subPrjId: row.subPrjId,
                onlyBe1Flag: parentNode.onlybe1flag,
                siteId: parentNode.siteId,
                serviceCode: parentNode.serviceCode,
                currentInspectionNum: currentInspectionNum,
                currentInspectionMoney: currentInspectionMoney,
                sumMoney: row.sumMoney || 0,
                sumNum: row.sumNum || 0,
                projectProgress: row.projectProgress || 0,
                inspectionTax: inspectionTax,
                inspectionTaxAmount: inspectionTaxAmount,
                orderDetailId: parentNode.orderDetailId,
                purchaseMode: parentNode.purchaseMode,
                payType: row.paymentType,
                flag: '1',
                month: this.query.month || '2023-11'
            }
            const res = await updateInsVaDetails(params)
            if (res.code === '200') {
                this.$message({
                    message: res.message,
                    type: 'success'
                })
            }
            this.queryInsValDetails12({
                prjId: this.prjId || '39994521',
                supplierCode: this.query.supplierCodes || '020100000307',
                month: this.query.months || '2023-11'
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.text-align-left {
    line-height: 25px;
    text-align: left;
}
::v-deep .el-table__fixed-right {
    height: 100% !important;
}

#messBox {
    word-break: break-all;
}
</style>
